<?php

namespace Apps\AppApi\Method\Question;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\Keyword;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\Question;
use Apps\Common\Models\QuestionAnswer;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\CosQKeyword;
use Apps\Common\Models\UserBase;
use Apps\Common\Libs\Jpush;
use Apps\Common\Models\QuestionAnswerComments;


/**
 * 添加问题答案
 * @package Apps\AppApi\Method\Question
 */
class AnswerAdd extends BaseMethod
{
    /**
     * @var \Apps\Common\Models\QuestionAnswer
     */
    private $success = 0;

    public function run()
    {
        /**
         * 验证用户权限
         */
        if(false == $this->verifyUserAuth()){
            return false;
        }

        $questionId = intval($this->getDataItem('question_id',0));
        $question_content = Keyword::Filter($this->getDataItem('content',''));
        $city_code = $this->getDataItem('city_code', '0');
        $original_content = $this->getDataItem('original_content', '');
        $to_user_id = intval($this->getDataItem('to_user_id', 0));

        if (!($question_content = trim($question_content))) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "回复内容不能为空！");
        }
        if($questionId > 0 && !empty($question_content)) {
            if (mb_strlen($question_content) > 300) {
                return $this->errorLog(ResultStatus::POST_BODY_FORMAT_ERROR, '回复内容长度不能超过300字符');
            }

            //关键字替换
            $keyword = CosQKeyword::query() -> execute() -> toArray();
            foreach ($keyword as $k => $v){
                $question_content = str_replace($v['keyword'], '***', $question_content);

            }
			$question_content = base64_encode(serialize($question_content));
            $up = new UploadPic();
            $user_id = $this->getUserAuth()->userId;
            $type = (new UserBase())->is_expert($user_id) ? 2 : 1; // 用户类型（1=》普通，2=》专家）
            if ($type == 2) { // 当前专家是否是首次回复
                $QuestionAnswerData = QuestionAnswer::query()->where("question_id = {$questionId} and user_id = {$user_id}")->execute()->getFirst();
                if (($answer_id = $QuestionAnswerData->answer_id ?: 0) && $QuestionAnswerData->type == 2) { // 不是首次回复
                    $datas = [
                        'question_id' => $questionId,
                        'answer_id' => $answer_id,
                        'content' => $question_content,
                        'pics' => json_encode($up->questionPic()),
                        'user_id' => $user_id,
                        'to_user_id' => $to_user_id,
                        'add_time' => date('Y-m-d H:i:s')
                    ];
                    $QuestionAnswerComments = new QuestionAnswerComments();
                    if ($QuestionAnswerComments->save($datas)) {
                        $this->setResult([
                            'question_id' => $questionId,
                            'success' => 1,
                            'files_count' => count($_FILES),
                        ]);
                        return true;
                    } else {
                        return $this->errorLog(ResultStatus::DATABASE_ERROR, '服务器异常！');
                    }
                }
            }
            $data = [
                'question_id' => $questionId,
                'user_id' => $user_id,
                'answer_content' => $question_content,
                'answer_pics' => json_encode($up->questionPic()),
                'answer_addtime' => date('Y-m-d H:i:s'),
                'city_code' => $city_code,
                'type' =>$type
            ];
            if ($original_content) {
                $data['original_content'] = $original_content;
            }

            $QuestionAnswer = new QuestionAnswer();

            if ($QuestionAnswer->save($data)) {
                $this->success = 1;
                $Question = new Question();
                $Question->setAnswerNum($questionId, 1, true);

                if ($type == 2) { // 修改问答为专家已回复状态
                    $Question->getReadConnection()->query('UPDATE question SET is_expert_reply = 1 WHERE question_id = ' . $questionId);
                }
            } else {
                return $this->databaseErrorLog($QuestionAnswer);
            }

        } else {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "缺少必传参数！");
        }
        //回答成功，推送消息
		$num = Question::query()
			->columns([
				'b.user_account',				
			])
			-> leftJoin('Apps\Common\Models\UserBase',
					'Apps\Common\Models\Question.user_id=b.user_id','b')
			-> where('Apps\Common\Models\Question.question_id = '.$questionId)
			-> execute()->toArray();
        $phoneNum = $num[0]['user_account'];
        $param['type'] = 6;
        $param['ispushservice'] = 0;
        $param['phone'] = $phoneNum;
        $param['message_link_type'] = 'question';
        $param['message_link_data'] = $questionId;
        $param['content'] = '您的问题有人回答了，快去看看吧！';
        $param['shop_id'] = 0;
        $push = new Jpush();
        $rs = $push -> setval($param);
        if(!empty($rs) || empty($phoneNum)){
        	$this->setResult([
        		'question_id' => $questionId,
        		'success' => $this->success,
        		'files_count' => count($_FILES),
        	]);       	
        }else{
       	
        	$rs = $push -> push();
            $this->setResult([
                    'question_id' => $questionId,
                    'success' => $this->success,
                    'files_count' => count($_FILES),
            ]);
        }
    }

}